package com.fysports.web.kit.jpush;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.google.common.collect.Maps;
import com.jfinal.json.Json;
import com.jfinal.log.Log;
import com.fysports.web.kit.commons.StringKit;
import com.fysports.web.model.app.AppPush;

import java.util.Map;


/**
 * Jpush推送工具
 * Created by konbluesky
 * Date : 15/7/5 下午7:55
 * Project :jdmdata_server
 */
public class JpushKit {
    private static Log logger = Log.getLog(JpushKit.class);
    /*Jpush 配置key*/
    //    public static final String MASTERSECRET="1b6d5ebbdea2e9717077bc73";
    //    public static final String APPKEY="c9a69802870635b702ca94e6";

    //konbluesky account
    public static final String MASTERSECRET = "5dba7dd1f9503e464f45ae0c";
    public static final String APPKEY = "cb4041ccfe9f8c4df0fb2466";


    /**
     * 推送
     *
     * @param app
     * @return
     */
    public static PushResult push(AppPush app) {
        if (app == null)
            throw new IllegalArgumentException("apppush推送对象不能为空");
        String context = app.get(AppPush.COL_MSGTEXT);
        String title = app.get(AppPush.COL_MSGTITLE);
        String platform = app.get(AppPush.COL_PLATFORM);

        PushPayload pp = create(context, title, platform);
        return push(pp);
    }


    public static PushResult push(PushPayload pp) {
        JPushClient jpushClient = new JPushClient(MASTERSECRET, APPKEY, 3);

        // For push, all you need do is to build PushPayload object.
        if (pp == null) {
            throw new IllegalArgumentException("PushPayload 不能为空");
        }
        PushResult result = null;
        try {
            result = jpushClient.sendPush(pp);
            logger.info("Got result - " + result);

        }
        catch (APIConnectionException e) {
            // Connection error, should retry later
            logger.error("Connection error, should retry later", e);

        }
        catch (APIRequestException e) {
            // Should review the error, and fix the request
            logger.error("Should review the error, and fix the request", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
        }
        return result;
    }


    /**
     * 创建PushPayload 对象
     *
     * @param context
     * @param title
     * @param platformstr
     * @return
     */
    private static PushPayload create(String context, String title, String platformstr) {
        Platform platform = null;
        if (platformstr != null && platformstr.equalsIgnoreCase("android")) {
            platform = Platform.android();
        }
        if (platformstr != null && platformstr.equalsIgnoreCase("ios")) {
            platform = Platform.ios();
        }
        if(StringKit.isBlank(platformstr) || platformstr.equalsIgnoreCase("all")) {
            platform=Platform.all();
        }

        PushPayload pp = new PushPayload.Builder().
                setPlatform(platform).
                setAudience(Audience.all()).
                setNotification(Notification.android(context, title, null)).build();
        return pp;
    }


    /**
     * 将主机推送上来的信息，推送到手机上
     * alert{
     * "loc-key':"xxxx",
     * "loc-args":["xxxx", "xxxx"]
     *
     * @param alias
     * @param loc_key
     * @param loc_args
     * @return
     */
    public static PushResult pushWarn(String alias, String loc_key, String... loc_args) {
        String[] args = loc_args;
        if (args == null || args.length == 0) {
            args = new String[] { "name", "host_sn" };
        }

        Map<String, Object> params = Maps.newHashMap();
        params.put("loc-key", loc_key);
        params.put("loc-args", args);
        String msg = "alert" + Json.getJson().toJson(params);

        Audience ali = Audience.alias(alias);
        if (alias == null || alias.length() == 0) {
            ali = Audience.all();
        }
        PushPayload pp = new PushPayload.Builder().
                setPlatform(Platform.all()).
                setAudience(ali).
                setMessage(Message.newBuilder().setMsgContent(msg).build()).build();
        return push(pp);
    }


    public static void main(String[] args) {
        PushResult pr = JpushKit.pushWarn("00606e017234", "DOOR_ILLEGAL_INTRUDING", null);
        System.out.println(pr.isResultOK());
    }

}
